//
//  GYDScanResultViewController.swift
//  Weibo
//
//  Created by 贵永冬 on 16/7/19.
//  Copyright © 2016年 贵永冬. All rights reserved.
//

import UIKit
import WebKit

class GYDScanResultViewController: UIViewController {

    lazy var resultLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 0, y: (self.view.height - 20)/2.0, width: self.view.width, height: 20))
        label.font = UIFont.systemFontOfSize(15)
        label.textColor = RGB(70, g: 70, b: 70)
        label.textAlignment = NSTextAlignment.Center
        return label
    }()
    var resultText : String?
    var webView : WKWebView?
    
    lazy var progressView : UIProgressView? = {
        let pro : UIProgressView = UIProgressView(frame: CGRect(x: 0, y: 64, width: self.view.width, height: 10))
        pro.progress          = 0.5
        pro.progressViewStyle = UIProgressViewStyle.Bar
        pro.progressTintColor = RGB(247, g: 169, b: 1)
        pro.trackTintColor    = UIColor.whiteColor()
        return pro
    }()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = BASECOLOR
        
        if (resultText!.hasPrefix("http:")){
            let url = NSURL(string: resultText!)
            let request = NSURLRequest(URL: url!)
            let web : WKWebView = WKWebView(frame: self.view.bounds)
            webView = web
            web.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.New, context: nil)
            view.addSubview(web)
            view.addSubview(progressView!)
            web.loadRequest(request)
        }else {
            self.resultLabel.text = resultText
            view.addSubview(self.resultLabel)
        }
    
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if progressView == nil {
            return
        }
        progressView!.progress = Float(webView!.estimatedProgress)
        if progressView!.progress == 1.0 {
            progressView!.hidden = true
            progressView!.removeFromSuperview()
            progressView = nil
        }
    }
    
    deinit {
        print("ssssss")
        if webView != nil {
            webView!.removeObserver(self, forKeyPath: "estimatedProgress", context: nil)
        }
        
    }
}
